#include "Defs.h"
#include "RuleByKey.h"


RuleByKey_T::RuleByKey_T(const char * szName, const char * szRootSection, const char * szConfigFile)
	: flag(false)
{
	FillMemory(_szName, sizeof(_szName), 0);
	_snprintf(_szName, sizeof(_szName) - 1, szName);

	flag = GetPrivateProfileInt(szRootSection, _szName, 1, szConfigFile) == 1;
	if( flag )
	{

		// 
		// Alloc buffer for Section Keys
		// Get section content
		//

		sectionData.Create(File_T::GetSize(szConfigFile));
		GetPrivateProfileSection(
			_szName, 
			(char *)sectionData.Ptr(),
			sectionData.Max(),
			szConfigFile);

		// 
		// Browse through the several entries
		//

		char * szLine = (char *)sectionData.Ptr();
		while( *szLine != '\0' )
		{
			char * szEqualSign = strchr(szLine, '=');
			if( szEqualSign )
			{
				*szEqualSign = '\0';

				tokenList.Add(new Buffer_T((unsigned char *)szLine, lstrlen(szLine)));
				numList.Add(new unsigned int(GetPrivateProfileInt(_szName, szLine, -1, szConfigFile)));

				szLine = szEqualSign + 1;
			}

			szLine += lstrlen(szLine) + 1;
		}
	}
}

void RuleByKey_T::ToString(char * szBuffer, unsigned int bufferSize)
{
	char szText[MAX_PATH];
	unsigned int bufferCursor = 0;

	if( flag )
	{
		_snprintf(szBuffer + bufferCursor, bufferSize - 1 - bufferCursor, 
			"# [%s]\r\n", _szName);
		bufferCursor = lstrlen(szBuffer);

		for( unsigned int ix = 0 ; ix < tokenList.Count() ; ix++ )
		{
			_snprintf(szBuffer + bufferCursor, bufferSize - 1 - bufferCursor, 
				"# \t%s=%d\r\n", tokenList[ix]->ToString(szText, sizeof(szText)), *numList[ix]);
			bufferCursor = lstrlen(szBuffer);
		}
	}
}